<template>
  <div class="purchase-products-list-component-page salesordeer-purchase-products">
    <div class="block">
      <header>
        <h2 class="required">
          {{ title ? title : '添加消耗产品' }}
        </h2>
      </header>
      <section class="salesorder-table">
        <el-row class="block-item">
          <el-col :span="12">
            <el-button type="primary" @click="onOpenImportProduct">
              模板导入
            </el-button>
            <el-divider direction="vertical" />
            <el-button type="text" @click="onGetProductTemplate">
              模板下载
            </el-button>
          </el-col>
          <el-col :span="12" class="right">
            <el-button type="primary" @click="onOpenProductDialog">
              添加销售产品
            </el-button>
          </el-col>
        </el-row>
        <el-editable
          :columns="SALESORDER_COLUMNS_PRODUCT"
          :payload="payload_products"
          :need-pagination="true"
          :row-class-name="'tableRowHospName'"
          height="400"
          @reload="reloadData"
        >
          <template v-slot:header-hospName="{ row, $index }">
            <span class="required">销售医院</span>
          </template>
          <template v-slot:default-productCount="{ row, $index }">
            <div>
              <el-input-number
                v-model="row.productCount"
                :step="1"
                size="medium"
                :min="0"
                :max="Number(row.availableQuantity || 1) > 999999999 ? 999999999 : Number(row.availableQuantity || 1)"
                @change="onChangeCount(row, $index)"
              />
              <span class="availableQuantity">可用量{{Number(row.availableQuantity) || 0}}</span>
            </div>
          </template>
          <template v-slot:default-validDate="{ row, $index }">
            <span >{{row.validDate || ''}} &nbsp;&nbsp;</span><span class="expiry_date" v-if="row.isCloseValidDate" >(近效期)</span>
          </template>
          <template v-slot:default-hospName="{ row, $index }">
            <div class="hosp_name_box">
              <el-autocomplete
                v-model="row.hospName"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
                @select="handleSelect($event, row, $index)"
              ></el-autocomplete>
            </div>
          </template>

          <template v-slot:default-opt="{ row, $index }">
            <a href="javascript:;" @click="onDeleteProduct(row, $index)">删除</a>
          </template>
          <!-- 给创建报台用的表格内表单 -->
        </el-editable>
      </section>
    </div>
    <upload ref="upload" :title-str="titleStr" :params="stepOneFormData" @repliceProducts="repliceProductsFn" @complete="getUploadProducts" />
  </div>
</template>

<script>
import { hospitalSearch, queryConfirmConsumptionProduct } from '@api/m_mall_web_v1.js';
import { ProductAddDialogService } from '~/modules/product/product-salesorder-add.dialog';
import * as CONSTS from './purchase-products-list.const';
import ElEditable from '@components/el-editable';
import { IndexService } from './purchase-products-list.service';
import { urlDownload } from '@const/utils';
const service = new IndexService();
import upload from '@/components/sales-upload';
import { debuglog } from 'util';
import { setTimeout } from 'timers';
import { numMulti } from '~/common'
export default {
  components: {
    ElEditable,
    upload
  },
  props: {
    titleStr: {
      type: String,
      default: '批发采购'
    },
    isCreateBill: {
      type: Boolean
    },
    stepOneFormData: {
      type: Object
    },
    products: {
      type: Array
    },
    type: {
      type: String,
      default: 'default'
    },
    operationType: String,
    title: String,
    supplierId: String,
    seqNoVoList: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      ...CONSTS,
      _products: [],
      payload_products: {},
      pager: {
        number: 1,
        size: 20
      },
      // 由于更新数量的动态性，下标的切换要同步。故这样搞
      index: {
        start: 1,
        end: 1
      },
      restaurants: [],
      timeout:  null,
    };
  },
  computed: {
    productAddDialogService: function() {
      return new ProductAddDialogService(this.$axios, this.$store, { type: this.type });
    }
  },
  watch: {
    products: {
      handler: function(val, oldVal) {
        if (val !== undefined) {
          this._products = val;
          this._products.map( (p, i)=> {
            if (p.productPrice !== '待定' && p.productPrice !== null) {
              let priceCount = numMulti(p.productPrice, p.productCount)
              priceCount = Math.floor(numMulti(priceCount, 100)) / 100
              if (Number.isInteger(priceCount)) {
                priceCount = priceCount.toString() + '.00'
              }
               p['priceCount'] = priceCount
            }
            // if (Number(p.availableQuantity) === 0) {
            //    this._products.splice(i,1)
            // }
          })
          let startIndex = (this.pager.number - 1) * this.pager.size;
          let endIndex = this.pager.number * this.pager.size;
          this.payload_products = service.getPayload(this._products, this.pager, startIndex, endIndex);
          this.payload_products.content.map( (p, i) => {
            p.index = i + 1
            p.oldProduct = p.productCount
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    hospitalSearch (queryString, cb) {
      this.$axios({
          url: hospitalSearch,
          method: 'post',
          data: {
            busModelCode: '2',
            hospitalName: queryString,
            supplierCode: this.supplierId
          }
        })
          .then(res => {
            if (res.data.code === '0') {
              let results = res.data.payload || []
              results.map(p => {
                p.value = p.hospitalName
                p.address =  p.hospitalCode
              })
              cb(results)
            }
          })
          .catch(err => {

          })
          .finally(() => {

          });
    },
    querySearchAsync(queryString, cb) {
      this.hospitalSearch(queryString, cb)
    },
    handleSelect($event, row, $index) {
       this.$nextTick(() => {
          this._products.map((p, i) => {
            if (i === $index) {
              p['hospName'] =  $event.value
            }
          })
        });
        this.$emit('removeSeqNoVoList', false)
        this.$emit('update:products', this._products);
    },
    repliceProductsFn () {
      this._products = []
      this.pager.number = 1
      this.$emit('update:products', this._products);
    },
    getUploadProducts(payload) {
      let loadProductList = payload;
      if (loadProductList.length > 0) {
        this.updateProductData(payload, true)
      }
    },
    // 前端分页逻辑
    reloadData(pager) {
      let startIndex = (pager.number - 1) * pager.size;
      let endIndex = pager.number * pager.size;
      this.payload_products = service.getPayload(this._products, pager, startIndex, endIndex);
      this.pager = pager;
      this.payload_products.content.map( (p, i) => {
        p.index = i + 1
      })
    },
    onDeleteProduct(row, index) {
       if (this.seqNoVoList.length > 0) {
         this.$confirm(`确定修改产品吗，将清空已添加的序列号`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            let startIndex = (this.pager.number - 1) * this.pager.size;
            let endIndex = this.pager.number * this.pager.size;
            this._products.splice(startIndex + index, 1);
            this.payload_products = service.getPayload(this._products, this.pager, startIndex, endIndex);
            if (this.payload_products.content.length === 0) {
              // 如果当前获取的内容为空，那么要重新获取一下数据
              this.pager.number = this.pager.number - 1;
              if (this.pager.number <= 0) this.pager.number = 1;
              let startIndex = (this.pager.number - 1) * this.pager.size;
              let endIndex = this.pager.number * this.pager.size;
              this.payload_products = service.getPayload(this._products, this.pager, startIndex, endIndex);
            }
            this.$emit('removeSeqNoVoList', false)
            this.$emit('update:products', this._products);
        }).catch(() => {
          //
        });

       } else{
          let startIndex = (this.pager.number - 1) * this.pager.size;
            let endIndex = this.pager.number * this.pager.size;
            this._products.splice(startIndex + index, 1);
            this.payload_products = service.getPayload(this._products, this.pager, startIndex, endIndex);
            if (this.payload_products.content.length === 0) {
              // 如果当前获取的内容为空，那么要重新获取一下数据
              this.pager.number = this.pager.number - 1;
              if (this.pager.number <= 0) this.pager.number = 1;
              let startIndex = (this.pager.number - 1) * this.pager.size;
              let endIndex = this.pager.number * this.pager.size;
              this.payload_products = service.getPayload(this._products, this.pager, startIndex, endIndex);
            }
       }
    },
    onChangeCount(row, index) {
        let oldProducts = row.oldProduct
        if (this.seqNoVoList.length > 0) {
          this.$confirm(`确定修改产品吗，将清空已添加的序列号`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

              if (Number(row.productCount) === 0 || row.productCount === undefined) {
                let oldProduct = row.oldProduct
                this.$nextTick(() => {
                  row.productCount = oldProduct;
                })
              }
              if (!Number.isInteger(Number(row.productCount))) {
                if (Number(row.productCount) > 0) {
                  let length =  (row.productCount).toString().split('.')[1].length
                  if (length > 4) {
                    this.$nextTick(() => {
                      // row.productCount = Math.floor((Number(row.productCount) * 10000)) / 10000
                      row.productCount = Math.floor(numMulti(row.productCount, 10000)) / 10000
                    })
                  }
                }
              }
              // 计算价格
              if (row.productPrice !== '待定') {
                this._products.map((p, i) => {
                if (i === index ) {
                    let priceCount = numMulti(p.productPrice, p.productCount)
                    priceCount = Math.floor(numMulti(priceCount, 100)) / 100
                    if (Number.isInteger(priceCount)) {
                      priceCount = priceCount.toString() + '.00'
                    }
                    this.$nextTick(() => {
                      p['priceCount'] = priceCount
                    })
                  }
                })
              }
              this.$emit('removeSeqNoVoList', false)
              this.$emit('update:products', this._products);
          }).catch(() => {
             let oldProduct = row.oldProduct
              this.$nextTick(() => {
                row.productCount = oldProducts;
              })
          });
        } else {
            if (Number(row.productCount) === 0 || row.productCount === undefined) {
              let oldProduct = row.oldProduct
              this.$nextTick(() => {
                row.productCount = oldProduct;
              })
            }
            if (!Number.isInteger(Number(row.productCount))) {
              if (Number(row.productCount) > 0) {
                let length =  (row.productCount).toString().split('.')[1].length
                if (length > 4) {
                  this.$nextTick(() => {
                    // row.productCount = Math.floor((Number(row.productCount) * 10000)) / 10000
                    row.productCount = Math.floor(numMulti(row.productCount, 10000)) / 10000
                  })
                }
              }
            }
            // 计算价格
            if (row.productPrice !== '待定') {
              this._products.map((p, i) => {
                if (i === index ) {
                  let priceCount = numMulti(p.productPrice, p.productCount)
                  priceCount = Math.floor(numMulti(priceCount, 100)) / 100
                  if (Number.isInteger(priceCount)) {
                    priceCount = priceCount.toString() + '.00'
                  }
                  this.$nextTick(() => {
                    p['priceCount'] = priceCount
                  })
                }
              })
            }
            this.$emit('update:products', this._products);
        }
    },
    onOpenProductDialog() {
      // 这里的formData传递完整的数据，再在子组件内整理成子级组件想要的数据格式，
      // 实际上这样做是“不好的”，但是由于数据的复杂度和混乱度，故此选择。
      // 再有一个原因是，产品搜索列表还需要一些额外的参数
      if (this.seqNoVoList.length > 0) {
        this.$confirm(`确定修改产品吗，将清空已添加的序列号`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
             this.productAddDialogService
              .create({
                title: '添加销售产品',
                query: { operationType: this.operationType, formData: this.stepOneFormData },
                confirmButtonClickHandler: (data = {}) => {
                  data.forEach(element => {
                    this.$set(element, 'productCount', 1);
                  });
                  this.updateProductData(data);
                }
              })
              .mount();
        }).catch(() => {
          //
        });
      } else {
        this.productAddDialogService
          .create({
            title: '添加销售产品',
            query: { operationType: this.operationType, formData: this.stepOneFormData },
            confirmButtonClickHandler: (data = {}) => {
              data.forEach(element => {
                this.$set(element, 'productCount', 1);
              });
              this.updateProductData(data);
            }
          })
          .mount();
      }
    },
    updateProductData(data, isImport) {
      this._products = service.reConcatSelectData(data, this._products, 'originalFactoryProductCode','batchNo', isImport);
      let startIndex = (this.pager.number - 1) * this.pager.size;
      let endIndex = this.pager.number * this.pager.size;
      this.payload_products = service.getPayload(this._products, this.pager, startIndex, endIndex);
        this.$emit('removeSeqNoVoList', false)
      this.$emit('update:products', this._products);
    },
    onOpenImportProduct() {
      if (this._products.length > 0) {
        let messageWord = '确定模板导入，将清空列表已添加的销售产品'
        if (this.seqNoVoList.length > 0) {
          messageWord += '和已导入的序列号'
        }
        this.$confirm(`${messageWord}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$refs.upload.dialog_visible = true;
          this.$emit('removeSeqNoVoList', true)
        }).catch(() => {
          //
        });

      } else {
         this.$refs.upload.dialog_visible = true;
      }
    },
    onGetProductTemplate() {
      urlDownload(
        'https://mt.heng-tai.com.cn/guoke-channel-aggregation-center/api/v1/files/download/qp5s099o0wkzxba5s1qd1vq5t2qce9ky.xlsx'
      );
    }
  }
};
</script>
<style lang="less">
.availableQuantity {
  color: red;
}
.hosp_name_box{
  position: relative;
  .el-autocomplete{
    width: 260px;
  }
  .required_ele{
    color: red;
    font-size: 22px;
  }
  .tableRowHospName{
    .tabel-table_2_column_20{
      .cell{
        color: red !important
      }
    }
  }
}
.expiry_date{
  color: red;
}
.salesordeer-purchase-products .salesorder-table{
  height: 600px;
}
</style>
